import React, { useRef, useState, useEffect } from 'react';
import { obj_str, useForm, ck_empty, NuiBt, IkInput, uPlc } from 'sui';
import { g_db, g_line, g_wsn } from 'db/state';
import { KeyBoard } from 'base/ctl/keyboard';
import { loc } from 'local';
import { get_gun, clear_gun } from 'base/api';

const Scan = ({ hcmd, open, setOpen, lok="确定" }) => {
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        if (!open) {
            return;
        }

        const id = setInterval(() => {
            uPlc(null, "get",
                {
                    line: g_line(),
                    sn: g_wsn(),
                },
                r => {
                    const ret = get_gun(r);
                    if (!ret) {
                        return;
                    }

                    setValue({msn: ret});
                    clear_gun();
                },
                e => setValue(null));
        }, 700);

        return () => clearInterval(id);
    }, [open]);

    const hcancel = () => {
        g_db.start_scan();
        setOpen(false);
    };

    const hok = () => {
        const ck = {
            msn: (v) => ck_empty(v, "请输入条码"),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        hcmd(obj_str(value, "msn"));
    };

    return (
        <div className="flex flex-col">
            <div className="ml-4">
                <IkInput label={loc("base_81")} name="msn" form={form} value={value} width="w-px-msn" disabled={true}/>
            </div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={hcancel}>取消</NuiBt>
                <NuiBt className="ml-8 mr-4" hcmd={hok}>{lok}</NuiBt>
            </div>
        </div>
    );
};

const Pcode = ({ hcmd, open, setOpen, lok="确定" }) => {
    const msn_ref = useRef(null);
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        setValue(null);
        msn_ref.current.focus();
    }, []);

    const hok = () => {
        const ck = {
            msn: (v) => ck_empty(v, "请输入条码"),
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        hcmd(obj_str(value, "msn"));
    };

    const lst = [
        {ref: msn_ref, k: "msn"},
    ];

    const hcancel = () => {
        g_db.start_scan();
        setOpen(false);
    };

    return (
        <div className="flex flex-col">
            <div className="ml-4">
                <IkInput label={loc("base_81")} name="msn" form={form} value={value} width="w-px-msn" href={msn_ref}/>
                <KeyBoard className="mt-3" lst={lst} value={value} setValue={setValue}/>
            </div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={hcancel}>{loc("base_36")}</NuiBt>
                <NuiBt className="ml-8 mr-4" hcmd={hok}>{lok}</NuiBt>
            </div>
        </div>
    );
};

export {Scan, Pcode};
